package main

import (
	"fmt"
	"github.com/streadway/amqp"
	"log"
	"mytest/mq/rabbitmq"
)

var (
	host             = "127.0.0.1"
	port             = "5672"
	username         = "guest"
	password         = "guest"
	exchangeReqName  = "e_rpc_req"
	exchangeRespName = "e_rpc_resp"
	queueReqName     = "test_q_req"
	args             = map[string]interface{}{"x-expires": 60000, "x-message-ttl": 60000}
)

func main() {

	err := rabbitmq.InitRabbitMq(host, port, username, password)
	if err != nil {
		panic(fmt.Sprintf("Failed to connect to RabbitMQ, err: %s", err))
	}
	ch, err := rabbitmq.Conn.Channel()
	if err != nil {
		panic(err)
	}
	defer func() {
		log.Println("server close mq conn")
		_ = rabbitmq.Conn.Close()
	}()
	err = ch.ExchangeDeclarePassive(exchangeReqName, "direct", false, false, false, false, nil)
	if err != nil {

		err = ch.ExchangeDeclare(exchangeReqName, "direct", false, false, false, false, nil)
	}
	if err != nil {
		fmt.Printf("server创建交换机失败,err: %s \n", err)
		return
	}
	//queue, err := ch.QueueDeclarePassive(queueReqName, false, false, false, false, args)
	//if err != nil {
	queue, err := ch.QueueDeclare(queueReqName, false, false, false, false, args)
	if err != nil {
		fmt.Printf("server创建队列失败,err:%s \n", err)
		return
	}
	//}
	defer func() {
		log.Println("server close mq channel")
		_ = ch.Close()
	}()
	if err != nil {
		fmt.Printf("server创建交换机失败,err:%s \n", err)
		return
	}
	err = ch.QueueBind(queueReqName, queue.Name, exchangeReqName, false, nil)
	if err != nil {
		fmt.Printf("server绑定队列失败,err:%s \n", err)
		return
	}
	_ = ch.Qos(1, 0, false)
	msgs, err := ch.Consume(queueReqName, queueReqName, false, false, false, false, args)
	if err != nil {
		fmt.Printf("server消费消息失败,err:%s \n", err)
		return
	}

	forever := make(chan bool)

	go func() {
		for d := range msgs {
			content := string(d.Body)
			log.Printf("server recived from [%s] : [ %s ] \n", d.CorrelationId, content)
			d.Ack(false)
			err = ch.Publish(
				exchangeRespName,
				d.ReplyTo,
				false,
				false,
				amqp.Publishing{
					ContentType:   "text/plain",
					CorrelationId: d.CorrelationId, //rpc
					Body:          []byte(" Good Job! "),
				},
			)
			if err != nil {
				fmt.Printf("server 发送消息失败,err:%s \n", err)
				break
			}
		}
	}()

	log.Printf(" [*] Awaiting RPC reqeusts")
	<-forever

}
